<template>
  <div>
    <li>
      <label>
        <input type="checkbox" :checked="todo.done" @change="check(todo.id)" />
        <span v-show="!todo.editor">{{ todo.title }}</span>
        <input
          type="text"
          v-show="todo.editor"
          @blur="handlerBlur(todo, $event)"
          ref="inputTitle"
        />
      </label>
      <button class="btn btn-danger" @click="isRemove(todo.id)">删除</button>
      <button
        class="btn btn-bianji"
        @click="handlerEditor(todo)"
        v-show="!todo.editor"
      >
        编辑
      </button>
    </li>
  </div>
</template>

<script>
import pubsub from "pubsub-js";

export default {
  name: "TodoItem",
  props: ["todo"],
  methods: {
    check(id) {
      this.$bus.$emit("checkTodo", id);
    },
    isRemove(id) {
      if (confirm("确认删除吗？")) pubsub.publish("deleteTodo", id);
    },

    handlerEditor(todo) {
      if (todo.hasOwnProperty("editor")) {
        todo.editor = true;
      } else {
        this.$set(todo, "editor", true);
      }
      this.$nextTick(function(){
        this.$refs.inputTitle.focus()
      });
    },
    handlerBlur(todo, e) {
      todo.editor = false;
      if (!e.target.value.trim()) return alert("输入不能为空");
      this.$bus.$emit("updateTitle", todo.id, e.target.value);
    },
  },
};
</script>

<style scoped>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}
li:hover {
  background-color: #ddd;
}
li:hover button {
  display: block;
}
</style>